title: Get ModelState outside of controller and ActionFilter
body: <p>Is there a way to access the <code>ModelStateDictionary</code> from DI (outside of a Controller or ActionFilter)?  I think I can make an ActionFilter that stores a reference to the <code>ModelStateDictionary</code> somewhere, so I can access it later elsewhere, but I want to know if there's a <em>conventional</em> way to access it, like there's <code>IHttpContextAccessor</code> for <code>HttpContext</code>.</p>
  
  <p>We have a web app that is a client to our api. The reason I want to do this is because I want to automatically add errors to the web app's <code>ModelState</code> from a <code>DelegatingHandler</code> used by our API client (a typed http client). The handler would watch every response from the API and, for the ones applicable (400 responses with custom error codes in the body, like "Name already taken"), add a message to the <code>ModelState</code>.</p>
  
  <p>So far I've tried asking for a <code>ControllerContext</code>, but it seems to be always null.</p>
  
  <pre><code>var controllerContext = _serviceProvider.GetService&lt;ControllerContext&gt;();
  controllerContext?.ModelState.AddModelError("", result.ErrorMessage);
  </code></pre>
  
  <p>I've also looked at all the registered services using the VS debugger, but I couldn't find anything promising.</p>
  
  <hr>
  
  <p><strong>Side note</strong> (quite a big one) regarding comments about SRP and separation of concerns: I don't think this violates SRP. The API client is a generic client implementation of our API, which can be consumed from anywhere (we currently use it on Xamarin and an ASP.NET Core MVC Web app - the one mentioned in this very question). However, the API client expects a <code>HttpClient</code> in its constructor, which means that its behavior can be modified by its consumers. </p>
  
  <p>The Web App, for example, uses DI to provide the <code>HttpClient</code> the API client needs. That <code>HttpClient</code> is setup to use two delegating handlers, one of which is the one I've described in this question.</p>
  
  <p>As to whether or not <code>ModelState</code> should be manipulated outside of controllers: well, that is exactly what libraries like <code>FluentValidation</code> (and ASP.NET default validation) does. </p>
  
  <p>As to whether or not <code>ModelState</code> should be manipulated in a <code>DelegatingHandler</code>: I think this is a somewhat more valid discussion. However, no one has really presented no argument as to why this is bad.</p>
  
  <p>As to wether or not this should be done "automatically": I think it's better having the code in one place than having to remember to do this every time in every action in every call to the api.</p>
  
  <p>As to whether or not these messages should be even put into the <code>ModelState</code>: well, if I go into that here this <em>side</em> note would become too big. Also, no one has really argued about this, so...</p>