【问题标题】:Converting Serverside C# to ASP.NET Web API将服务器端 C# 转换为 ASP.NET Web API
【发布时间】:2014-09-05 19:45:39
【问题描述】:

在发布了如何将服务器端信息发送到 JS(在客户端)link here 之后,我被建议将服务器端逻辑创建到 Web Api 中,以便通过 JQuery AJAX 调用通过 HTTP 公开数据。在查看了大量文档,甚至是tutorial series online hosted by Microsoft 之后,我发现几乎没有什么好的指导。以前,我在我的 js 脚本中通过内联 C# 调用来调用我的服务器端方法,但了解到因为 C# 是预编译的,它只是“填充”C# 函数返回的值。

仅供参考,以了解我如何不正确地调用我的 C# 方法。

这是我的前端:Login.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>PAM testing</title>
    <link rel="stylesheet" type="text/css" href="Styles/Site.css" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
    <script type="text/javascript" src="Scripts/JScript.js"></script>
</head>
<body>
    <div id="banner">PAM Testing Tool</div>
    <div id="content">
        <form id="form1" runat="server" style="margin-left: 25%; text-align: center; height: 41px; width: 292px;">
            <%--Login ASP Object--%>
            <asp:Login ID="Login1" runat="server" onclick="process()"></asp:Login>
            <asp:ValidationSummary ID="ValidationSummary1" runat="server" style="text-align: center" ValidationGroup="Login1" />
        </form>

        <%--TEST AREA--%>
        <script type="text/javascript">

            function logCookie(){
                document.cookie = "user=" + document.getElementById("Login1_UserName").value;// this is the id of username input field once displayed in the browser
            }

            function testFunction() {
                <%=Login1_Authenticate() %>;
            }

            function process(){
                logCookie();
                testFunction();
            }

        </script>
    </div>
</body>

</html>

我的 C# 代码如下所示

Login.aspx.cs

using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.EnterpriseServices;

public partial class Login : System.Web.UI.Page
{
    int status;
    int role;
    SqlConnection conn;
    SqlCommand command;
    SqlDataReader reader;


    protected string Login1_Authenticate()
    {

        // create an open connection
        conn =
            new SqlConnection("Data Source=xxx;"
            + "Initial Catalog=xxx;"
            + "User ID=xxx;Password=xxx");

        conn.Open();

        //string userName;
        //userName = Convert.ToString(Console.ReadLine());


        // create a SqlCommand object for this connection
        command = conn.CreateCommand();
        command.CommandText = "EXEC dbo.SP_CA_CHECK_USER @USER_ID = '"+Login1.UserName+"', @PASSWORD = '"+Login1.Password+"'";
        command.CommandType = CommandType.Text;

        // execute the command that returns a SqlDataReader
        reader = command.ExecuteReader();

        // display the results
        while (reader.Read())
        {
        status = reader.GetInt32(0);
        }

        // close first reader
        reader.Close();

        //----------
        existTest();
        return "the login process is finished";

    }


    public static string GetData(int userid)
    {
        /*You can do database operations here if required*/
        return "my userid is" + userid.ToString();
    }

    public string existTest()
    {
        if (status == 0)
        {
            //login
            Session["userID"] = Login1.UserName;



            command.CommandText = "EXEC dbo.SP_CA_RETURN_USER_ROLE @USER_ID = '" + Login1.UserName + "'";
            reader = command.ExecuteReader();
            while (reader.Read())
            {
                role = reader.GetInt32(0);
            }

            Session["roleID"] = role;

            if (Session["userID"] != null)
            {
                string userID = (string)(Session["userID"]);
                //string roleID = (string)(Session["roleID"]);
            }
            Response.Redirect("Home.aspx");
        }
        else
        {
            //wrong username/password
        }



        // close the connection
        reader.Close();
        conn.Close();
        return "process complete";
    }
}

如何将我的 C# 转换为 Web api?如果有任何答案可以将我链接到好的文档或教程,我将非常感激。

【问题讨论】:

标签: javascript c# asp.net asp.net-web-api


【解决方案1】:

将其移动到 Web API 需要创建一个新的 Web API 项目,设置适当的控制器,并将表单控件移动到参数以传递给控制器​​方法。有关 ASP.NET Web MVC 入门的更多信息,请访问本教程:Getting Started With ASP-NET Web API

请注意:以您在上述代码中的方式执行动态 SQL 会使您的应用程序容易受到SQL Injection 攻击!请考虑改用参数化 SQL。

【讨论】:

    猜你喜欢
    • 2012-03-23
    • 2017-05-14
    • 1970-01-01
    • 2013-10-24
    • 1970-01-01
    • 1970-01-01
    • 2013-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多