title: Why am I receiving a 401 Unauthorized in my C# ASP.net MVC Web API?
body: <p>I have a C# asp.net MVC project, that will be used as a Web API to call SharePoint 2013 endpoints. I have gone ahead and configured SharePoint with a developer site, added the proper app information to both the App.manifest and web.config files in the project, registered the app with the SharePoint site, and created/set up a certificate for the Token Issuer. As far as I can tell, and yes I've checked a few times, that all the proper info has been entered in the proper locations.</p>
  
  <p>The code I'm trying to run is as follows:</p>
  
  <pre><code>[SharePointApiControllerContextFilter]
  [HttpPost]
  [Route("api/testapi/search/{id}")]
  public System.Web.Http.Results.JsonResult&lt;string&gt; Search(string id)
  {
      var spContext = SharePointApiControllerContextProvider.Current.GetSharePointContext(ControllerContext);
      string data = string.Empty;
  
      using (var clientContext = spContext.CreateUserClientContextForSPHost())
      {
          if (clientContext != null)
          {
              try
              {
                  string url = spContext.SPHostUrl + "_api/search/query?querytext='" + HttpUtility.HtmlEncode(id) + "'";
                  Uri uri = new Uri(url);
  
                  HttpWebRequest searchReq = (HttpWebRequest)HttpWebRequest.Create(uri);
                  searchReq.Accept = "application/json;odata=verbose";
  
                  String username = "username";
                  String password = "password";
                  String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));
  
                  searchReq.Headers.Add("Authorization", "Basic " + encoded);
  
                  HttpWebResponse results = (HttpWebResponse)searchReq.GetResponse();
                  var stream = results.GetResponseStream();
  
                  var readStream = new StreamReader(stream, Encoding.UTF8);
                  var content = readStream.ReadToEnd();
                  return Json&lt;string&gt;(content);
              }
              catch (WebException we)
              {
                  return Json&lt;string&gt;(we.ToString());
              }
              catch (Exception e) {
                  return Json&lt;string&gt;(e.ToString());
              }
          }
      }
      return Json&lt;string&gt;(data);
  }
  </code></pre>
  
  <p>Within IIS on the server, only Basic Authentication, ASP.net Impersonation, and Forms Authentication are enabled.</p>
  
  <p>Everything seems to be set up correctly, but with my basic auth request, I always get a 401 unauthorized response from SharePoint. I've also noticed the actual API endpoint is endlessly redirecting when being visited from a web browser directly.</p>
  
  <p>Would somebody help me fix my issue(s) with the API and the endpoints? Thanks.</p>