有时我在向WebService执行HttpWebRequest时遇到以下错误.我也复制了下面的代码.
System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: No connection could be made because the target machine actively refused it 127.0.0.1:80 at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) --- End of inner exception stack trace --- at System.Net.HttpWebRequest.GetRequestStream()
ServicePointManager.CertificatePolicy = new TrustAllCertificatePolicy();
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.PreAuthenticate = true;
request.Credentials = networkCredential(sla);
request.Method = WebRequestMethods.Http.Post;
request.ContentType = …Run Code Online (Sandbox Code Playgroud) .net c# socketexception system.net.webexception asp.net-web-api2
我们假设这是我的行动方法
public IHttpActionResult Get(int id)
{
var status = GetSomething(id);
if (status)
{
return Ok();
}
else
{
return NotFound();
}
}
Run Code Online (Sandbox Code Playgroud)
测试将是
var httpActionResult = controller.Get(1);
Run Code Online (Sandbox Code Playgroud)
如何在此之后检查我的http状态代码?
首先,我将描绘我的项目:
对于我的实习船,我需要为现有系统添加功能.一旦用户通过oauth2授权,第三方客户端必须能够访问AX Web服务中的数据.我知道我需要建立一个"代理Web服务",客户端可以在其中进行调用并调用AX服务,但我对oauth2部分有点不确定.大多数教程和指南都是关于在Facebook或谷歌登录中使用ASP.NET的标识.我不需要,我需要使用现有的凭据,所以我需要自己创建oauth2服务.
我发现很难找到关于此的教程,指南或解释.我理解oauth2以及需要做什么,但我以前从未做过这样的事情并且发现它很难开始.我发现的最接近我需要的是这个github repo链接,但解决方案没有构建.
我想到的是建立一个ASP.NET MVC网站,客户(第三方)可以自己注册并获取他们的客户ID.使用ASP.NET API,我想创建获取所需令牌和参数的API,然后访问Dyn AX服务.
这是正确的还是我完全错了?有关构建您自己的oauth2服务器/服务的任何帮助或链接都会很好.
刚升级ASP.NET MVC4项目以使用Unity.WebApi版本5.0.0.0,它需要System.Web.Http v 5.0.0.0,因为以下错误:
Assembly 'Unity.WebApi, Version=5.1.0.0, Culture=neutral, PublicKeyToken=43da31bc42a85347' uses 'System.Web.Http, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' which has a higher version than referenced assembly 'System.Web.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
Run Code Online (Sandbox Code Playgroud)
我目前正在引用System.Web.Http v4.0但是将以下NuGet包升级到各自的最新版本:
WebGrease
通过NuGet.我没有列出相关的JavaScript库,如Micrososft.jQuery.Unobtrusive Validation等.
什么是升级System.Web.Http的NuGet包,还是我必须手动执行此操作?
我试图让工作的URL是以下风格的网址:http://somedomain.com/api/people/staff.33311(就像网站一样,LAST.FM允许在他们的RESTFul和WebPage网址中添加所有类型的标记例如," http://www.last.fm/artist/psy'aviah "是LAST.FM的有效网址.
以下方案有效: - http://somedomain.com/api/people/ - 返回所有人 - http://somedomain.com/api/people/staff33311 - 也可以,但不是我的意思在我希望网址接受"点"后,就像下面的示例 - http://somedomain.com/api/people/staff.33311 - 但这给了我一个
HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
Run Code Online (Sandbox Code Playgroud)
我已经设置了以下内容:
控制器"PeopleController"
public IEnumerable<Person> GetAllPeople()
{
return _people;
}
public IHttpActionResult GetPerson(string id)
{
var person = _people.FirstOrDefault(p => p.Id.ToLower().Equals(id.ToLower()));
if (person == null)
return NotFound();
return Ok(person);
}
Run Code Online (Sandbox Code Playgroud)WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
// …Run Code Online (Sandbox Code Playgroud)c# asp.net-mvc-routing asp.net-mvc-4 asp.net-web-api asp.net-web-api2
UPDATE
感谢所有的答案.我正在进行一个新项目,看起来我终于找到了底层:看起来下面的代码实际上应该归咎于:
public static HttpResponseMessage GetHttpSuccessResponse(object response, HttpStatusCode code = HttpStatusCode.OK)
{
return new HttpResponseMessage()
{
StatusCode = code,
Content = response != null ? new JsonContent(response) : null
};
}
Run Code Online (Sandbox Code Playgroud)
别处...
public JsonContent(object obj)
{
var encoded = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore } );
_value = JObject.Parse(encoded);
Headers.ContentType = new MediaTypeHeaderValue("application/json");
}
Run Code Online (Sandbox Code Playgroud)
假设它是WebAPI,我忽略了看似无害的JsonContent但没有.
这在任何地方都可以使用......我能说第一个,wtf吗?或许应该是"为什么他们这样做?"
原始问题如下
人们会认为这将是一个简单的配置设置,但现在我已经躲过太久了.
我看过各种解决方案和答案:
https://gist.github.com/rdingwall/2012642
似乎不适用于最新的WebAPI版本......
以下似乎不起作用 - 属性名称仍然是PascalCased.
var json = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
json.UseDataContractJsonSerializer = true;
json.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
json.SerializerSettings.ContractResolver …Run Code Online (Sandbox Code Playgroud) 我想要以下架构(我已经为这个例子编写了产品名称):
在一台服务器 http://api.prettypictures.com 上运行的Web API 2应用程序
MVC 5客户端应用程序在另一台服务器上运行 http://www.webpics.com
我希望www.webpics.com客户端应用程序使用Pretty Pictures API:
所有上述工作除了在Facebook,Google等注册外部账户外.
我无法确定从API的单独客户端用户创建外部帐户的正确流程.
我已经研究了认证流程中可用的大多数文档,如下所示:

我已经在OWIN的新身份模型上阅读了我所能做的一切.
我已经在Visual Studio 2013中检查了SPA模板.它演示了如何完成我需要的大部分工作,但仅限于客户端和API在同一主机上时; 如果我希望多个客户端访问我的API并且能够让用户通过Google等注册,那么它就无法正常工作,而且我可以告诉OWIN身份验证流程中断.
到目前为止流程如下:
这是我被卡住的地方.接下来应该发生的是以某种方式通知客户端应用程序用户已成功通过google.com进行身份验证,并获得一次性访问代码以便稍后交换访问令牌.如有必要,客户端应用程序应该有机会提示用户输入与google.com登录相关联的用户名.
我不知道如何促进这一点.
实际上,此时浏览器在谷歌回调后最终坐在api.prettypictures.com/Account/ExternalLogin端点上.该API已登录Google,但客户端不知道如何处理该问题.我应该将该饼干送回www.webpics.com吗?
在SPA应用程序中,它通过AJAX完成,google.com将返回一个令牌作为URL片段,它一切运行良好,因为它都在一个域上.但这远远超过了拥有多个客户可以充分利用的"API"的重要性.
救命!
asp.net-mvc oauth-2.0 owin asp.net-identity asp.net-web-api2
我尝试按照http://enable-cors.org/server_aspnet.html中的步骤 使我的RESTful API(使用ASP.NET WebAPI2实现)与跨源请求(CORS Enabled)一起工作.除非我修改web.config,否则它无法正常工作.
我安装了WebApi Cors依赖:
install-package Microsoft.AspNet.WebApi.Cors -ProjectName MyProject.Web.Api
Run Code Online (Sandbox Code Playgroud)
然后在我App_Start的课程中我得到WebApiConfig如下:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
var corsAttr = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(corsAttr);
var constraintsResolver = new DefaultInlineConstraintResolver();
constraintsResolver.ConstraintMap.Add("apiVersionConstraint", typeof(ApiVersionConstraint));
config.MapHttpAttributeRoutes(constraintsResolver);
config.Services.Replace(typeof(IHttpControllerSelector), new NamespaceHttpControllerSelector(config));
//config.EnableSystemDiagnosticsTracing();
config.Services.Replace(typeof(ITraceWriter), new SimpleTraceWriter(WebContainerManager.Get<ILogManager>()));
config.Services.Add(typeof(IExceptionLogger), new SimpleExceptionLogger(WebContainerManager.Get<ILogManager>()));
config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler());
}
}
Run Code Online (Sandbox Code Playgroud)
但之后我运行应用程序,我请求Fiddler的资源,如: http:// localhost:51589/api/v1/persons ,在响应中,我看不到我应该看到的HTTP头,例如:
Access-Control-Allow-Methods: POST, PUT, DELETE, GET, OPTIONSAccess-Control-Allow-Origin: *我错过了一步吗?我在控制器上尝试了以下注释:
[EnableCors(origins: "http://example.com", headers: "*", methods: "*")]
相同的结果,没有启用CORS. …
是的,我知道你在想什么 - 还有另一个CORS问题,但这次我很难过.
所以要开始,实际的错误信息:
XMLHttpRequest无法加载http://localhost/Foo.API/token.当请求的凭据模式为"include"时,响应中"Access-Control-Allow-Origin"标头的值不能是通配符"*".因此不允许来源' http:// localhost:5000 '访问.XMLHttpRequest发起的请求的凭据模式由withCredentials属性控制.
我不确定凭证模式的含义是'包含'?
所以当我在邮递员中执行请求时,我没有遇到这样的错误:
但是当我通过我的angularjs网络应用程序访问相同的请求时,我被这个错误所困扰.这是我的angualrjs请求/回复.你会看到响应OK 200,但我仍然收到CORS错误:
小提琴请求和响应:
下图演示了Web前端到API的请求和响应
所以基于我在网上阅读的所有其他帖子,看起来我做的是正确的,这就是为什么我无法理解错误.最后,这是我在angualrjs(登录工厂)中使用的代码:
API中的CORS实现 - 参考目的:
方法1使用:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
EnableCrossSiteRequests(config);
}
private static void EnableCrossSiteRequests(HttpConfiguration config)
{
var cors = new EnableCorsAttribute("*", "*", "*")
{
SupportsCredentials = true
};
config.EnableCors(cors);
}
}
Run Code Online (Sandbox Code Playgroud)
方法2使用:
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration(); …Run Code Online (Sandbox Code Playgroud) 当我尝试开始时:
WebApp.Start<SrvcHst>(new StartOptions { Port = 9956,
ServerFactory = "Microsoft.Owin.Host.HttpListener" });
Run Code Online (Sandbox Code Playgroud)
我得到以下异常.可能是根本原因?
System.MissingMemberException was caught
HResult=-2146233070
Message=The server factory could not be located for the given input: Microsoft.Owin.Host.HttpListener
Source=Microsoft.Owin.Hosting
StackTrace:
at Microsoft.Owin.Hosting.Engine.HostingEngine.ResolveServerFactory(StartContext context)
at Microsoft.Owin.Hosting.Engine.HostingEngine.Start(StartContext context)
at Microsoft.Owin.Hosting.Starter.DirectHostingStarter.Start(StartOptions options)
at Microsoft.Owin.Hosting.Starter.HostingStarter.Start(StartOptions options)
at Microsoft.Owin.Hosting.WebApp.StartImplementation(IServiceProvider services, StartOptions options)
at Microsoft.Owin.Hosting.WebApp.Start(StartOptions options)
at Microsoft.Owin.Hosting.WebApp.Start[TStartup](StartOptions options)
Run Code Online (Sandbox Code Playgroud) asp.net-web-api2 ×10
c# ×8
.net ×3
cors ×2
oauth-2.0 ×2
owin ×2
.net-4.5 ×1
angularjs ×1
asp.net ×1
asp.net-mvc ×1
exception ×1
javascript ×1
json.net ×1
nuget ×1
rest ×1