标签: asp.net-web-api

webapi 中的错误 - 无法从“System.Web.Mvc.JsonRequestBehavior”转换为“Newtonsoft.Json.JsonSerializerSettings”

在 webapi jsonrequestbehaviour 中不起作用,显示无法将“System.Web.Mvc.JsonRequestBehavior”转换为“Newtonsoft.Json.JsonSerializerSettings”

代码

 public ActionResult AddTemprature(string EmployeeName, int EmployeeId, string Location)
        {
            try
            {

                using (EmployeeDBEntities DB = new EmployeeDBEntities())
                {

                    WebApi.Employee emp = new WebApi.Employee();
                    // EmployeeModel Emp = new EmployeeModel();
                    emp.EmpName = EmployeeName;
                    emp.EmpId = EmployeeId;
                    emp.EmpLocation = Location;
                    DB.Employees.Add(emp);
                    DB.SaveChanges();
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception Ex)
            {

            }
            return Json(false, JsonRequestBehavior.AllowGet);
        }
Run Code Online (Sandbox Code Playgroud)

c# asp.net-mvc json asp.net-mvc-4 asp.net-web-api

1
推荐指数
1
解决办法
5408
查看次数

HttpContext.Response.OutputStream 在 WebAPI 的 HttpResponseMessage 中使用的替代方法是什么

我正在编写一个用于处理 PDF 文档的 WebAPI。它是在之前实现 IHttpHandler 并使用 HttpContext 获取上下文的 ashx 页面中编写的。我现在正在使用 WebAPI 编写它。在 WebAPI 中,我们有 HttpResponseMessage。对于 HttpContext.Response.BinaryWrite,我们在 HttpResponseMessage 中有新的 ByteArrayContent。但是 WebAPI 中 HttpContext.Response.OutputStream 的替代方案是什么?我需要在 WebAPI 中使用 OutputStram 的替代方案,因为我将此 OutputStream 作为参数传递给另一个 dll。

ashx 中的代码:

SomeReport.PdfReport rpt = new SomeReport.PdfReport(docID);
rpt.CreateReport(context.Response.OutputStream);
Run Code Online (Sandbox Code Playgroud)

asp.net-web-api httpresponsemessage

1
推荐指数
1
解决办法
3051
查看次数

DELETE动词在iis 10中不起作用

DELETE 方法在 IIS 10 中显示以下错误

请求的资源上不存在“Access-Control-Allow-Origin”标头。

所有其他方法(如 POST 和 GET)都可以正常工作。此外,DELETE 在开发时在 iis express 中运行良好。我为 WebApiConfig 类中的所有请求启用了 cors

public static void Register(HttpConfiguration config)
{
    config.SuppressDefaultHostAuthentication();
    config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

    // Web API routes
    config.MapHttpAttributeRoutes();
    var cors = new EnableCorsAttribute("*", "*", "*");
    config.EnableCors(cors);
    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{action}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
Run Code Online (Sandbox Code Playgroud)

我的网络配置看起来像这样

<?xml version="1.0" encoding="utf-8"?> <!--   For more information on how to configure your ASP.NET application, please visit   http://go.microsoft.com/fwlink/?LinkId=301879   --> <configuration>   <configSections>
    <!-- For more information on Entity Framework …
Run Code Online (Sandbox Code Playgroud)

iis cors http-delete asp.net-web-api iis-10

1
推荐指数
1
解决办法
2428
查看次数

Swagger UI - 使用 Microsoft.AspNet.WebApi.Versioning 时的 Web API 版本控制

我们在Swagger项目中使用Web API 2。我的问题是,当Microsoft.AspNet.WebApi.Versioning应用如下:

在此处输入图片说明

扬鞭UI被忽略的事实是,现在我在的API,它需要提供具有版本。

我看了几个例子,但似乎没有一个能以令人满意的方式解决这个问题。

如何强制 Swagger 让我添加 API 版本或仅将版本号自动添加到 URL?

到目前为止的 Swagger 配置:

GlobalConfiguration.Configuration
                .EnableSwagger(c =>
                {

                    c.SingleApiVersion("v1", "MoovShack.ServerApi");

                    // If your API has multiple versions, use "MultipleApiVersions" instead of "SingleApiVersion".
                    // In this case, you must provide a lambda that tells Swashbuckle which actions should be
                    // included in the docs for a given API version. Like "SingleApiVersion", each call to "Version"
                    // returns an "Info" builder so you can …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-web-api swagger swagger-ui

1
推荐指数
1
解决办法
8386
查看次数

HttpClient 发送空的 POST 数据

嗯...我在 StackOverflow 中阅读了很多问题,但仍然没有得到答案,我有这个 Web API 控制器:

public class ERSController : ApiController
{
    [HttpGet]
    public HttpResponseMessage Get()
    {
        var resposne = new HttpResponseMessage(HttpStatusCode.OK);
        resposne.Content = new StringContent("test OK");
        return resposne;
    }

    [HttpPost]
    public HttpResponseMessage Post([FromUri]string ID,[FromBody] string Data)
    {
        var resposne = new HttpResponseMessage(HttpStatusCode.OK);
        //Some actions with database
        resposne.Content = new StringContent("Added");
        return resposne;
    }

}
Run Code Online (Sandbox Code Playgroud)

我给它写了一个小测试:

static void Main(string[] args)
{
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri("http://localhost:54916/");
    client.DefaultRequestHeaders.Accept.Clear();


    var content = new StringContent("<data>Hello</data>", Encoding.UTF8, "application/json");

    var response …
Run Code Online (Sandbox Code Playgroud)

c# httpclient asp.net-web-api

1
推荐指数
1
解决办法
4888
查看次数

c# asp.net web api中的模型验证日期格式

我正在使用模型映射 web api Get 请求复杂类型输入参数,我想验证模型中输入类型的日期格式。

我输入的uri如下 http://localhost:xxxx/api/games/?id=5&date=2018-01-17

在我的游戏控制器中

public IHttpActionResult Get([FromUri]Gamedata) {

 if (ModelState.IsValid) {
 }
 else {

 }
}
Run Code Online (Sandbox Code Playgroud)

在我的模型课上

public class Game
    {
        [Required]
        public int? Id { get; set; }

        [Required]
        public string date { get; set; } // Validate the date format "YYYY-MM-DD"


}
Run Code Online (Sandbox Code Playgroud)

我想验证日期格式“YYY-MM-DD”。如何实现?我正在阅读这个。但是不知道要使用哪个注解?

c# asp.net-web-api asp.net-web-api2

1
推荐指数
1
解决办法
4005
查看次数

在 ASP.custom 中间件中初始化对象并注入它们

我有一个 ASP.NET Core Web API,它读取请求标头中的身份验证令牌并解码其中的值。

我已经编写了自定义中间件来解码令牌。我还创建了一个 UserContext 对象来保存从令牌解码的值,并将解码的值设置到 UserContext 对象中。

我现在希望能够将 UserContext 对象(在自定义中间件中创建)注入我的控制器,但我无法弄清楚如何做到这一点。

请帮忙。

asp.net-web-api .net-core asp.net-core

1
推荐指数
1
解决办法
1075
查看次数

C# 不包含“内容”的定义

我创建了一个接受用户输入为 xml 的服务,如果缺少任何参数,我必须返回一个视图,允许用户输入缺少的详细信息。

所以我认为使用 api 控制器返回视图是不可能的,所以我使用了 mvc 控制器。但是当我读取xml时显示以下错误。

C# 不包含“Content”的定义,并且找不到接受第一个类型参数的扩展方法“Content”(您是否缺少 using 指令或程序集引用?)

这是我的代码

public class MyController : Controller 
{
   public IHttpActionResult MyService([FromUri] TestProperty testProperty)
    {
       string DataXML = this.Request.Content.ReadAsStringAsync().Result;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是

1.如何解决这个错误?

2.有没有其他方法可以使用api控制器来满足我的需求?将视图返回给用户并接受 xml。

xml asp.net-mvc asp.net-web-api

1
推荐指数
1
解决办法
4458
查看次数

Web Api - 同时执行少量请求时响应速度非常慢

我有一个 Web API C# 项目。我注意到当向控制器发送很少的请求时(很少有甚至 7-10 个),一些请求需要很长时间(5-7 秒)。单独发送每个请求时,每个请求耗时不到200ms。我正在向我的本地主机(开发环境)发送请求,因此服务器上不应该有任何延迟或大量使用。

我在 global.asax 中添加了这段代码,以查看每个请求需要多长时间。

//Global asax

 private Dictionary<string, StopWatch> urlTimers = new Dictionary<string, StopWatch>();
    void Application_BeginRequest(object sender, EventArgs e)
    {
        HttpContextBase currentContext = new HttpContextWrapper(HttpContext.Current);
        var requestedUrl = currentContext.Request.RequestContext.HttpContext.Request.RawUrl;
        var urlWithoutQueryParams = requestedUrl.Split('?')[0];
        if (urlWithoutQueryParams.StartsWith("/controller"))
        {
            var stopWatch = new StopWatch();
            stopWatch.Start(urlWithoutQueryParams);
            urlTimers[urlWithoutQueryParams] = stopWatch;
        }

     
    }

    void Application_EndRequest(object sender, EventArgs e)
    {
        HttpContextBase currentContext = new HttpContextWrapper(HttpContext.Current);
        var requestedUrl = currentContext.Request.RequestContext.HttpContext.Request.RawUrl;
        var urlWithoutQueryParams = requestedUrl.Split('?')[0];
        if (urlWithoutQueryParams.StartsWith("/controller"))
        {
            var stopWatch = urlTimers[urlWithoutQueryParams]; …
Run Code Online (Sandbox Code Playgroud)

c# asp.net asp.net-web-api

1
推荐指数
1
解决办法
4272
查看次数

我如何使用多种简单类型 PostAsync()?

我如何使用多个简单类型作为参数 PostAsync(),我有下面的动作控制器:

[HttpPost]
[Route("users/verifyLoginCredentials/{username}/{password}")]
public IHttpActionResult VerifyLoginCredentials([FromUri]string username, string password)
{

   //Do Stuff......
   return Ok("Login Successful");

}
Run Code Online (Sandbox Code Playgroud)

我正在尝试从 .Net Framerwork 4.5 客户端应用程序调用它,如下所示:

static async Task<Uri> CreateProductAsync(string username, string password)
{


     HttpClient client = new HttpClient();
     client.BaseAddress = new Uri(uri);
     client.DefaultRequestHeaders.Accept.Clear();
     client.DefaultRequestHeaders.Accept.Add(
            new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded"));
     client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));

     var value = new Dictionary<string, string>
     {
        { "username", "test123" }
     };

     var content = new FormUrlEncodedContent(value);
     var result = await client.PostAsync("users/verifyLoginCredentials/{username}/{password}", content);
     string resultContent = await result.Content.ReadAsStringAsync();

     result.EnsureSuccessStatusCode();

     // return URI of the …
Run Code Online (Sandbox Code Playgroud)

c# asp.net-web-api

1
推荐指数
1
解决办法
7506
查看次数