标签: asp.net-web-api

导出到Excel作为Web API中的响应

我正在使用Web API 4.5.1.我在C#代码中生成API并将此API传递到前端,其前端基于HTML和AngularJS JavaScript构建.我的要求是创建一个API,用于导出到Excel的前端.我是一个被困在这里的人.我收到前端人员的请求,包括fromdate和todate.基于此,我将查询数据库以获取数据,如果我成功,则从中获取HTML格式.因为我是新手,我无法继续前进.下面是我试图通过以下方式实现此目的的代码:

[HttpPost]
public HttpResponseMessage ExportToExcel(string fromTimeStamp, string toTimeStamp)
{
    DateTime fromDate = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
    fromDate = fromDate.AddMilliseconds(Convert.ToDouble(fromTimeStamp)).ToLocalTime();
    fromDate.AddDays(1);

    DateTime toDate = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
    toDate = toDate.AddMilliseconds(Convert.ToDouble(toTimeStamp)).ToLocalTime();
    toDate.AddDays(1);

    var fromDate1 = fromDate.AddDays(1).ToString("yyyy-MM-dd");
    var toDate1 = toDate.AddDays(1).ToString("yyyy-MM-dd");

    var bal = new AdminBAL();
    var ExportData = bal.ExportToExcel(fromDate1, toDate1);
    //where Exportdata is the html format for the data required.
    // unable to find the solution here
} …
Run Code Online (Sandbox Code Playgroud)

c# export-to-excel asp.net-web-api angularjs

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

如何更改Asp.NET MVC中的控制器命名约定?

我开始在asp.NET MVC中开发.我需要将Web API与View项目分开,我希望WebAPI控制器具有来自View项目的不同命名约定,以便从用于视图的控制器轻松识别什么是webapi控制器.在这两个项目中,默认约定是name +'Controller'.如果有一种方法可以在webapi中更改它,例如,而不是'WebAPiController',我希望名称约定为'WebAPICtrl'ou'WebAPiService'.

我发现它关闭的问题是: 在ASP.NET MVC中更改控制器名称约定

如何在Asp.net mvc 5中存档此要求?

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

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

如何在ASP.NET Web API 2.0中验证电子邮件?

请提供正则表达式来验证web api方法中的电子邮件ID,如下所示:

// GET: users/sample%40email.com
[Route("users/{emailAddress:regex()}")] 
public IHttpActionResult GetUser(string emailAddress)
Run Code Online (Sandbox Code Playgroud)

在这里,我需要正则表达式,它将验证电子邮件,如示例%40email.com,并将工作:web api路由属性的regex().

asp.net asp.net-web-api

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

OData Web API 404错误

我是odata的新手。我已经用控制器构建了一个Web api,如下所示:

using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Web.OData.Routing;

namespace HelloWebApi.Controllers
{
public class TestsController : ODataController
{
    //
    // GET: /Product/

    ProductsContext db = new ProductsContext();
    private bool TestExists(int key)
    {
        return db.tests.Any(p => p.key== key);
    }
    protected override void Dispose(bool disposing)
    {
        db.Dispose();
        base.Dispose(disposing);
    }

    [EnableQuery]
    public IQueryable<test> Get()
    {
        return db.tests;
    }
Run Code Online (Sandbox Code Playgroud)

模型如下图所示:

 public class Test
    {
       [Key]
    public int key { get; set; }
    public string aaa { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我还配置了routeconfig,odataconfig,webapi config和global.asax文件,如下所示。

public class RouteConfig …
Run Code Online (Sandbox Code Playgroud)

odata asp.net-web-api

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

即使使用$ top,也强制订购OData项目

我有一个DbSet<Items>集合.

主键是Guid.我不想通过这个主键订购.我想通过名为"Order"的可编辑十进制属性进行排序.

我所拥有的代码非常简单,在用户将"$ top"参数放入请求之前,它非常有用:

public class ItemsController : ApiController
{
    protected DbContext ctx = // ...

    // GET api/documents
    [EnableQuery()]
    public IQueryable<Item> Get()
{
    return ctx.Items.OrderBy(o => o.Order).AsQueryable();
}
Run Code Online (Sandbox Code Playgroud)

当用户将"$ top"放入查询字符串时,订单会全部搞乱(这可能会强制排序由主键完成,以获得一致的分页结果 - 但是,在我的情况下,这是相反的效果,它阻止我有一致的分页结果).

我已经尝试过移动.AsQueryable()到查询的早期(在.OrderBy(...)子句之前),我已经尝试过没有了.AsQueryable(),我已经尝试了两个AsQueryables等.

这个表中会有很多项目,所以需要通过一个来完成IQueryable(枚举Web服务器上的所有项目IEnumerable都不是一个选项).

到目前为止唯一有用的是从客户端传递"$ orderby = Order",但我不想强迫它(似乎很容易被遗忘).

1.)我可以做些什么来使我的Order财产订购这里的默认行为?

2.)或者失败了,无论如何,是否有人欺骗WebApi/OData认为自定义了"$ orderby = Order"子句?

linq entity-framework iqueryable odata asp.net-web-api

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

Web API 2中的文件上传问题,然后是html表单帖子

Web API 2中的文件上载问题

虽然我上传文件与表格发布此工作文件,但我发送来自Rest Client的相同信息,如Google Chrome中的Postman或使用Android或iOS应用程序发布文件信息Web Api 2代码未检测到文件multipart/form-post

以下是我的HTML代码

    <form enctype="multipart/form-data" method="post" action="/api/feedback">
    <input type="text" name="Scope" placeholder="Scope" value="feedback">
    <input type="text" name="Lang" placeholder="Lang" value="en">
    <input type="text" name="Collection" placeholder="Collection" value="7b22437573746f6d65724964223a392c2253657276696365526571756573744964223a312c224174746974756465223a332e322c22576f726b457468696373223a342e322c2248796769656e65223a352c22416d6f757450616964223a333132332e327d">
    <input type="file" name="Photo1" placeholder="Photo1">
    <input type="file" name="Photo2" placeholder="Photo2">
    <input type="file" name="Signature" placeholder="Signature">
    <input type="submit" value="Submit">
</form>
Run Code Online (Sandbox Code Playgroud)

这个.Net Web Api 2代码

        public async Task<Result> Post()
    {
        var model = new ApiData();
        var result = new Result();
        if (Request.Content.IsMimeMultipartContent())
        {
            try
            {
                string root = HttpContext.Current.Server.MapPath("~/assets/temp");
                var provider = new MultipartFormDataStreamProvider(root);

                var sb = …
Run Code Online (Sandbox Code Playgroud)

asp.net-web-api asp.net-mvc-5

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

MultipartMemoryStreamProvider并从MultiPart / Form数据读取用户数据

我有一个文件和用户数据,这些文件和用户数据已从Multipart / form数据发布到apicontroller类中的post方法。我能够毫无问题地读取文件,但无法读取用户数据。

我尝试了几种方法,例如使用模型绑定,在post方法中将各个字段作为方法参数传递,但是我得到:没有MediaTypeFormatter可从媒体类型为“ multipart / form-data”的内容中读取“ FormDataCollection”类型的对象'。

var provider = await Request.Content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider());
foreach (var item in provider.Contents)
{
    var fieldName = item.Headers.ContentDisposition.Name.Trim('"');
    if (item.Headers.ContentDisposition.FileName == null)
    {
        var data = await item.ReadAsStringAsync();
        if (fieldname == "name")
        { 
            Name = data;
        }
        else
        {
            fileContents = await item.ReadAsByteArrayAsync();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

谢谢。

html asp.net-mvc-4 asp.net-web-api asp.net-web-api2

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

ApiController中的Url.Route不包含主机名

ApiController,我正在生成一个通过电子邮件发送给用户的密码重置链接.一切正常,但Url.Route函数不会生成与主机名的链接.我不确定是不是因为我正在使用localhost它导致问题.

这是生成链接的代码

string callbackUrl  = Url.Route("DefaultApi", new { controller = "Account", action= "ResetPassword", UserId = user.Id, code = code });
Run Code Online (Sandbox Code Playgroud)

这是生成的链接

https:///api/Account/ResetPassword?UserId=aaaaaaaaaa&code=aaaaaaaaa
Run Code Online (Sandbox Code Playgroud)

注意https:///api,它应该包括主机名和端口之类的https://localhost:4040/api.为什么不包含主机名?

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

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

Owin WebApi 2主机名IntegratedAuth失败 - 400错误和错误的凭据

我有一个使用OWIN自托管的Intranet应用程序来提供SPA/WebAPI 2类型的站点.一切都很好,如localhost:port和IP:port,但是IE和Chrome的主机名:端口都失败了.然而,该应用程序适用于FireFox.

我相信这是由于集成身份验证.Chrome返回ERR_INVALID_AUTH_CREDENTIALS,IE返回400错误请求.Fiddler在请求/响应的标头中没有显示出太大差异,除了身份验证通过,我得到一个200的FF,一个400的IE和一个401的Chrome.

我的大多数代码都是从SO文章或MSDN教程中"借用"的.这是我的Program.cs:

string baseAddress = "http://*:9000/";
using (WebApp.Start<Startup>(new StartOptions(baseAddress) { ServerFactory =  "Microsoft.Owin.Host.HttpListener" }))
{
    // Keep server operational till stopped
    Console.WriteLine("Started, Press any key to stop.");
    Console.ReadKey();
    Console.WriteLine("Stopped");
 }
Run Code Online (Sandbox Code Playgroud)

这是我的startup.cs:

public void Configuration(IAppBuilder appBuilder)
{
    var listener = (HttpListener)appBuilder.Properties["System.Net.HttpListener"];
    listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;

    // Configure Web API for self-host. 
    HttpConfiguration config = new HttpConfiguration();

    WebApiConfig.Register(config);
    appBuilder.UseWebApi(config);
    appBuilder.UseFileServer(new FileServerOptions
    {
        RequestPath = new PathString(string.Empty),
        //  path to static files.
        FileSystem = new PhysicalFileSystem("./public"),
        EnableDirectoryBrowsing = false
    });
}
Run Code Online (Sandbox Code Playgroud)

我还确保使用netsh设置网址预留: …

c# authentication httplistener asp.net-web-api owin

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

从Android到Web API的POST数据返回404

我正在尝试将来自我的Android客户端的数据作为POST请求发送到我的Web API后端,但它返回404响应代码.这是我的代码:

后端:

[HttpPost]
[Route("api/postcomment")]
public IHttpActionResult PostComment(string comment, string email, string actid)
{
       string status = CC.PostNewComment(comment, email, actid);
       return Ok(status);
}
Run Code Online (Sandbox Code Playgroud)

Android代码:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://MYWEBADDRESS.azure-mobile.net/api/postcomment");
String mobileServiceAppId = "AZURE_SERVICE_APP_ID";

try {

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        nameValuePairs.add(new BasicNameValuePair("comment", comment));
        nameValuePairs.add(new BasicNameValuePair("email", currEmail));
        nameValuePairs.add(new BasicNameValuePair("actid", currActID));

        httppost.setHeader("Content-Type", "application/json");
        httppost.setHeader("ACCEPT", "application/json");
        httppost.setHeader("X-ZUMO-APPLICATION", mobileServiceAppId);

        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairs);
        httppost.setEntity(formEntity);

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);

} 
catch (Exception e) …
Run Code Online (Sandbox Code Playgroud)

asp.net rest android asp.net-web-api azure-mobile-services

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