Make Web API authentication return 401 instead of redirect to login page
<p>I have Web API with OWIN Authentication in Web MVC.
I'm using <code>&lt;authentication&gt;</code> in Web.Config for my Web MVC so it's redirecting to login page.</p>

<pre><code>&lt;authentication mode="Forms"&gt;
    &lt;forms name="WEB.AUTH" loginUrl="~/login" domain="" protection="All" 
    timeout="43200" path="/" requireSSL="false" slidingExpiration="true" /&gt;
&lt;/authentication&gt;
</code></pre>

<p>I'm using <code>[System.Web.Http.Authorize]</code> attribute to authorize my Web API. But somehow, the API redirecting to login page same like my MVC app because of above configuration.</p>

<p>what I want to do is keep redirecting function for the Web MVC but returning 401 for Web API. How can I achieve this? should I create a custom authorization attribute for Web API?</p>

<p><strong>--EDIT--</strong></p>

<p>I found the answer from this post <a href="https://stackoverflow.com/questions/21878446/suppressdefaulthostauthentication-in-webapi-owin-also-suppressing-authentication">SuppressDefaultHostAuthentication in WebApi.Owin also suppressing authentication outside webapi</a></p>

<p>So I just add a few lines into my <code>Startup.cs</code>. I had all my controllers configured with a "api" prefix route.</p>

<pre><code>HttpConfiguration config = new HttpConfiguration();
//..some OWIN configuration
app.Map("/api", inner =&gt;
{
  inner.UseWebApi(config);
});
</code></pre>

<p>make sure you put <code>app.Map()</code> after Web Api Configuration lines. Otherwise, it will give error to MVC application.</p>