我有一个服务,几乎每个方法都需要当前用户执行。在我开始使用 autofac 之前,我基本上创建了一个像这样的公共属性:
private IOrderProvider _orderProvider;
public IOrderProvider OrderProvider => _orderProvider ?? (_orderProvider = new OrderProvider((ClaimsIdentity)User.Identity));
Run Code Online (Sandbox Code Playgroud)
因为这是控制器上的公共属性,所以它可以访问User。现在使用 autofac 我在StartupConfig中注册我的服务。当然,我无权访问那里的用户。
有没有办法将当前用户注入到OrderProvider构造函数中,或者有其他方法来获取它?
我的 webApi 在其中使用第三方 Web api 服务。问题是它在我的本地计算机和 Azure Web 服务中完美运行。但是当我将此解决方案转移到 Azure Vm 实例时,出现此错误。我已经安装了与第 3 方 Web api 相关的正确证书并注册了 HttpClient 并尝试了
ServicePointManager.Expect100Continue = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11;
Run Code Online (Sandbox Code Playgroud)
但它给出了同样的错误。我不知道确切的错误是什么。有人可以帮忙解决这个问题吗?
我在将图像上传到我正在运行的 Web API 时遇到问题。使用 GET 请求时,我可以从 Web API 检索数据,但在处理 POST 请求时遇到问题。我需要将 BMP 图像上传到 Web API,然后发回 json 字符串。
[HttpPost]
public IHttpActionResult TestByte()
{
Log("TestByte function entered");
//test to see if i get anything, not sure how to do this
byte[] data = Request.Content.ReadAsByteArrayAsync().Result;
byte[] test = Convert.FromBase64String(payload);
if(test == null || test.Length <= 0)
{
Log("No Payload");
return NotFound();
}
if (data == null || data.Length <= 0)
{
Log("No payload");
return NotFound();
}
Log("Payload received");
return Ok();
}
Run Code Online (Sandbox Code Playgroud)
发送图像的 MVC …
Json.Net没有将其接收到的对象反序列化为我的 Control 类的正确派生类。(请参阅以下对该问题的解释。另请注意,我认为这是解释该问题所需的最少代码量。提前感谢您审阅此问题。)
我正在尝试将以下类序列化为 JSON 或从 JSON 反序列化。
public class Page {
public Guid Id { get; set; }
public Guid CustomerId { get; set; }
public IList<Control> Controls { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这是 Control 类:
public class Control : ControlBase
{
public override Enums.CsControlType CsControlType { get { return Enums.CsControlType.Base; } }
}
Run Code Online (Sandbox Code Playgroud)
这是 ControlBase 抽象类:
public abstract class ControlBase
{
public Guid Id { get; set; }
public virtual Enums.CsControlType CsControlType { get; }
public …Run Code Online (Sandbox Code Playgroud) 我有一个 ASP.NET Web API 2 操作方法:
[System.Web.Http.HttpPost]
public HttpResponseMessage Create(HttpRequestMessage req)
{
//...
if (success)
return Request.CreateResponse(HttpStatusCode.Created);
return CreateErrorResponse(HttpStatusCode.BadRequest, "you done bad");
}
Run Code Online (Sandbox Code Playgroud)
直到我做了“某事”,一旦出错,它就会返回 http 400,并带有自定义错误文本“you did bad”。这就是预期的结果。
它不再返回自定义文本;它只是返回标准的“错误请求”。一直在试图了解是什么改变导致了这种情况的发生。
所以我尝试:
var response = new { message = "you done bad" };
return Request.CreateResponse(HttpStatusCode.BadRequest, response);
Run Code Online (Sandbox Code Playgroud)
相同的结果。
然后我创建了一个新的、干净的 Web API 项目,并得到了我期望的结果。
我是如何破坏我的项目的?
我有一个简单的模型,例如:
public class Employer
{
[Required(ErrorMessage = "Please specify id")]
public int Id { get; set; }
[MaxLength(256, ErrorMessage = "Max lenght should be less than 256")]
[Required(ErrorMessage = "Please specify Name")]
public string Name { get; set; }
[Required(ErrorMessage = "Please specify id of organization")]
public int OrganizationId { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
那么控制器是:
public IHttpActionResult Post(Employer employer)
{
if(!IsActiveOrganization(employer.OrganizationId))
{
ModelState.AddModelError(nameof(employer.OrganizationId), "The organization is not active!");
}
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的,我正在尝试在创建新雇主之前验证模型。因此,当我传递无效模型时id,响应将如下:
{ …Run Code Online (Sandbox Code Playgroud) 我在 jQuery 中有这个函数
var uri = "api/queries";
function test(){
var params = {
origin: $('#depair').val(),
destination: $('#destair').val(),
departure_date: $('#depdate').val(),
currency: $('#currency').val(),
}
$.getJSON(uri, params)
.done(function (data) {
console.log(data);
});
}
Run Code Online (Sandbox Code Playgroud)
它将请求发送到此Controller:
public class QueriesController : ApiController
{
[HttpGet]
public string GetInfo()
{
return "blah";
}
}
Run Code Online (Sandbox Code Playgroud)
所以,请求看起来像这样
http://localhost:55934/api/queries?origin=&destination=&departure_date=¤cy=
如何从控制器GetInfo方法内部访问请求的参数?
以下是我在WebApi .Net Core 2项目中的ActionFilter:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class RequestLoggingAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext actionContext)
{
var request = actionContext.HttpContext.Request;
var route = request.Path.HasValue ? request.Path.Value : "";
var requestHeader = request.Headers.Aggregate("", (current, header) => current + $"{header.Key}: {header.Value}{Environment.NewLine}");
request.EnableRewind();
var requestBody = new StreamReader(request.Body).ReadToEnd();
}
}
Run Code Online (Sandbox Code Playgroud)
requestHeader具有正确的值并且可以,但requestBody始终为空。
我通过将带有以下正文的请求发送到操作来测试它。
[
{
"TrackingCode": "96003445",
"Description": "",
"InnerMessage": "",
"Status": 11
},
{
"TrackingCode": "96003840",
"Description": "",
"InnerMessage": "Inner message",
"Status": 11
}
]
Run Code Online (Sandbox Code Playgroud)
如何在 WebApi …
asp.net-web-api asp.net-core asp.net-core-webapi .net-core-2.0
有没有办法将 EntitySet 动态添加到 ODataConventionModelBuilder。
我正在 .net 中开发 OData 服务。我们将返回的一些实体来自外部程序集。我很好地阅读了程序集并获取了相关类型,但由于这些类型是变量,我不确定如何将它们定义为实体集。
例子:
public static void Register(HttpConfiguration config)
{
//some config house keeping here
config.MapODataServiceRoute("odata", null, GetEdmModel(), new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer));
//more config housekeeping
}
private static IEdmModel GetEdmModel()
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.Namespace = "SomeService";
builder.ContainerName = "DefaultContainer";
//These are the easy, available, in-house types
builder.EntitySet<Dog>("Dogs");
builder.EntitySet<Cat>("Cats");
builder.EntitySet<Horse>("Horses");
// Schema manager gets the rest of the relevant types from reading an assembly. I have them, now I just need to create entity …Run Code Online (Sandbox Code Playgroud) 我有以下格式的数组,我需要将其发布到 API:
console.log(addserverList);
我想将其传递给 api 的 post 方法
const options = {headers: {'Content-Type': 'application/json'}};
return this.http.post( 'http://localhost:54721/api/BulkUpload/SaveBulkUploadData',addserverList,options)
Run Code Online (Sandbox Code Playgroud)
我可以发布到 api,但数据传递始终显示为 NULL
模型 i 的结构如下:
生成数组的函数
private extractData(res: Response) {
let csvData = res['_body'] || '';
let allTextLines = csvData.split(/\r\n|\n/);
let headers = allTextLines[0].split(',');
let lines = [];
for ( let i = 0; i < allTextLines.length; i++) {
// split content based on comma
let data = allTextLines[i].split(',');
if (data.length == headers.length) {
let tarr = [];
for ( let j …Run Code Online (Sandbox Code Playgroud) asp.net-web-api ×10
c# ×7
asp.net-mvc ×4
.net ×2
angular ×1
asp.net ×1
asp.net-core ×1
autofac ×1
azure ×1
jquery ×1
json ×1
json.net ×1
modelstate ×1
odata ×1
ssl ×1
validation ×1